#include "Animation.h"

using namespace vn;

Animation::Animation(const std::string& p_id, int p_row, int p_frameRate, int p_startupFrame, int p_startFrame, int p_endFrame, int p_timesRepeat, bool p_repeat, bool p_reverse, bool p_reverseWhenRepeat) : 
	m_id(p_id), m_frameRate(p_frameRate), m_startupFrame(p_startupFrame), m_currentFrame(p_startupFrame), m_startFrame(p_startFrame), m_endFrame(p_endFrame), m_timesRepeat(p_timesRepeat), m_repeat(p_repeat), 
	m_reverse(p_reverse), m_reverseWhenRepeat(p_reverseWhenRepeat), m_frameInc(1), m_pause(false), m_done(false), m_oldTime(0), m_previousFrame(0), m_row(p_row)
{
	if (m_timesRepeat > 0)
		m_fixedRepeat = true;
	if (p_reverse)
		m_currentFrame = p_endFrame;
}

Animation::~Animation(void){ m_id.clear(); }

void Animation::update(const GameTime& p_gameTime)
{
	if (!m_pause && !m_done)
	{
		m_oldTime += p_gameTime.getElapsedTimeAsMilliseconds();				// add time
		if (static_cast<int>(m_oldTime) >= m_frameRate)		// if time is larger than framerate, increment frame.
		{
			m_oldTime = 0;
			if (!m_reverse)
			{
				m_previousFrame = m_currentFrame;
				m_currentFrame += m_frameInc;
			}
			else
			{
				m_previousFrame = m_currentFrame;
				m_currentFrame -= m_frameInc;
			}
		}

		if (!m_reverse)
		{
			if (m_currentFrame > m_endFrame)				
			{
				if (m_repeat)
				{
					if (m_reverseWhenRepeat)
					{
						m_reverse = true;
					}
					else
					{
						m_currentFrame = m_startFrame;
					}
				}
				else
				{
					m_done = true;
					m_currentFrame = m_endFrame;
				}
			}
		}
		else
		{
			if (m_currentFrame < m_startFrame)
			{
				if (m_repeat)
				{
					if (m_reverseWhenRepeat)
					{
						m_reverse = false;
					}
					else
					{
						m_currentFrame = m_endFrame;
						m_currentFrame = m_startFrame;
					}
				}
				else
				{
					m_done = true;
					m_currentFrame = m_startFrame;
				}
			}
		}
	}
}

void Animation::reset()
{
	m_done = false;
	m_currentFrame = m_startupFrame;
	m_oldTime = 0;
}

const bool Animation::hasFrameChanged() const
{
	if (m_previousFrame == m_currentFrame)
		return false;
	return true;
}